package com.architecture.core.service.associate;

import com.architecture.core.entity.Category;
import com.architecture.core.entity.User;
import com.architecture.core.except.ErrException;
import com.architecture.core.service.AbstractService;
import com.architecture.core.utils.ErrCode;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: aguang
 * Date: 13-1-21
 * Time: 下午6:13
 * To change this template use File | Settings | File Templates.
 */
@Service("manageUserService")
public class UserAssociateService extends AbstractService {

    public void associateCategory(String userId,String categoryId) throws ErrException{

        if (StringUtils.isBlank(userId)) {
            throw new ErrException(ErrCode.BLANK_ID);
        }

        if (StringUtils.isBlank(categoryId)) {
            throw new ErrException(ErrCode.BLANK_ID);
        }

        User user = (User)this.baseDAO.findUnique(User.class, userId);

        Category category = (Category) this.baseDAO.findUnique(Category.class, categoryId);

        user.getCategoryList().add(category);
        category.getUserList().add(user);

        this.baseDAO.update(user);
        this.baseDAO.update(category);
    }

    public void associateCategory(String userId,List<String> categoryIdList) throws ErrException{

        if (CollectionUtils.isEmpty(categoryIdList)) {
            throw new ErrException(ErrCode.EMPTY_COLLECTION);
        }

        for (String categoryId : categoryIdList) {
            this.associateCategory(userId,categoryId);
        }
    }

    public void deassociateCategory(String userId,String categoryId) throws ErrException{
        if (StringUtils.isBlank(userId)) {
            throw new ErrException(ErrCode.BLANK_ID);
        }

        if (StringUtils.isBlank(categoryId)) {
            throw new ErrException(ErrCode.BLANK_ID);
        }

        User user = (User)this.baseDAO.findUnique(User.class, userId);

        Category category = (Category) this.baseDAO.findUnique(Category.class, categoryId);

        user.getCategoryList().remove(category);
        category.getUserList().remove(user);

        this.baseDAO.update(user);
        this.baseDAO.update(category);
    }

    public void deassociateCategory(String userId,List<String> categoryIdList) throws ErrException{
        if (CollectionUtils.isEmpty(categoryIdList)) {
            throw new ErrException(ErrCode.EMPTY_COLLECTION);
        }

        for (String categoryId : categoryIdList) {
            this.deassociateCategory(userId, categoryId);
        }
    }
}
